<?php

namespace addons\yiliao\controller\api;

use app\common\controller\Api;
use fast\Http;
use think\Db;
//use app\common\library\Auth;
//use think\Lang;
use app\admin\model\yiliao\Useropenid;

class Base extends Api
{
    protected $noNeedLogin = ['*'];// 无需登录即可访问的方法，同时也无需鉴权了
    protected $noNeedRight = ['notify','bookingnotify'];// 无需鉴权即可访问的方法
    protected $token='';
    protected $apiurl="";
    protected $user="";
    protected $setting="";
    protected $sessionid="";
    
    public function _initialize()
    {
        parent::_initialize();
        check_cors_request();

        $this->apiurl = $this->request->domain();
        $this->sessionid = $this->request->header('sessionid');
        $this->token = $this->request->header('token');

        $this->setting = get_addon_config('yiliao');
        $action=$this->request->action();
        if ($this->setting['token']!= $this->token && !in_array($action, $this->noNeedRight)) {
            $this->success('success', '');
        }
        
        if ($this->sessionid) {
            $this->user = Useropenid::where(['session_key'=>$this->sessionid])->field('id,openid,userid')->find();
        }
        // 载入语言包、初始化Auth等

        //这里手动载入语言包
        //Lang::load(ROOT_PATH . '/addons/zx/lang/zh-cn.php');
    }

    public function getaccess()
    {
        $cache = \think\Cache::tag('yiliao')->get('accezxoken');
        if ($cache) {
            return $cache;
        } else {
            $setting = $this->setting;
            $api = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$setting['appid'].'&secret='.$setting['appsecret'];
            $res = Http::post($api);
            $json = json_decode($res, true);
            if (isset($json['errcode'])) {
                $this->error('获取失败');
            } else {
                \think\Cache::tag('yiliao')->set('accezxoken', $json, 7000);
            }
            return $json;
        }
    }
}
